;(function(){
  var workingGroup = {
    init:function(){
      var self = this;
      self.event()
      self.isShowMenu()
      self.configNodeUsers()
      self.removeSelectedMember()
      self.fzrDropdown()
    },
    // 工作组成员
    assigneesData:{
      'userIds':[],
      'userNames':[]
    },
    // 已选组员
    selectedMember:[],
    // 租户下的用户
    tenantsUser:[],
    // 编辑保存
    saveEdit:function(){
      if(!this.validateWorking())return
      var self = this;
      var groupId = JSON.parse(window.localStorage.getItem('wgData')).groupId

      var data = {
        id:groupId,
        name:$('.grp-ipt').val().trim(),
        leader_id:$('.fzr').attr('data-id'),
        leader_name:$('.fzr').attr('data-name'),
        leader_phone:$('.fzr').attr('data-tel'),
        user_ids:self.assigneesData.userIds.join(',')
      }

      hlhttp.put({
        url:'data_group',
        headers:{token:Cookies.get("token")},
        data:data,
        success:function(data){
          vueMethod.pagesearch()
          hl.toast('编辑成功')
          $('.wkp-pop').hide()
          $('.backdrop').hide()
          self.clearData()
        }
      })
    },
    // 新建保存
    saveCreate:function(){
      var self = this;
      if(!self.validateWorking())return
      var data = {
        name:$('.grp-ipt').val().trim(),
        leader_id:$('.fzr').attr('data-id'),
        leader_name:$('.fzr').attr('data-name'),
        leader_phone:$('.fzr').attr('data-tel'),
        user_ids:self.assigneesData.userIds.join(',')
      }
      hlhttp.post({
        url:'data_group',
        data:data,
        success:function(data){
          vueMethod.pagesearch()
          hl.toast('新建成功')
          $('.wkp-pop').hide()
          $('.backdrop').hide()
          self.clearData()
        }
      })
    },
    // 保存验证
    validateWorking:function(){
      if(!$('.grp-ipt').val().trim()){
        hl.toast('工作组名称不能为空')
        return false;
      }
      if(!$('.fzr').val()){
        hl.toast('负责人名称不能为空')
        return false;
      }
      if(!$('.fzr').attr('data-id')){
        hl.toast('请填写用户中存在的负责人')
        $(this).val('')
        return false;
      }
      return true;
    },
    // 查看工作组
    getGroupMes:function(){
      var self = this;
      var groupId = JSON.parse(window.localStorage.getItem('wgData')).groupId

      hlhttp.get({
        url:'data_group/' + groupId + '/info,user_info',
        success:function(data){
          $('.grp-ipt').val(data.name)
          $('.fzr').val(data.leaderName)
          $('.fzr').attr('data-name',data.leaderName).attr('data-id',data.leaderId).attr('data-tel',data.leaderPhone)
          self.selectedMember = data.users
          if(data.users.length !== 0){
            data.users.map(function(_item){
              self.assigneesData.userIds.push(_item.userId)
              self.assigneesData.userNames.push(_item.userName)
            })
            self.dom.memberList(self.selectedMember)
          }else{
            $('.no-member').show()
          }

        }
      })
    },
    // 获取组织架构节点数据
    // id:父级菜单ID index:菜单级别 containerNode:菜单容器 isUsers:加载对子级菜单是否为成员 默认为false
    getOrganizationNodeData:function (id,index,containerNode,isUsers,member) {
      var self = this;
      var dtd = $.Deferred();
      isUsers = isUsers || false;

      if(!isUsers){
        hlhttp.get({
          url: 'sub_organizations',
          data: {pid: id},
          success: function (data) {
            if(data.length){
              data.map(function (_item) {
                _item['index'] = index
              })
              self.dom.organizationNode(data,containerNode)
            }
            dtd.resolve(data);
          }
        })
      }
      if(isUsers){
        hlhttp.get({
          url: 'organization/users',
          data: {organization_id: id},
          success: function (data) {
            var newData = []
            if(data.length){
              data.map(function (_item) {
                var _obj = {};
                _obj['index'] = index;
                _obj['id'] = _item.userId;
                _obj['shortName'] = _item.userName;
                _obj['userPhone'] = _item.userPhone;
                _obj['userAccount'] = _item.userAccount;
                _obj['type'] = 'CY';
                newData.push(_obj)
              })
              self.dom.memberNode(newData,member,containerNode)
            }
            dtd.resolve(data);
          }
        })
      }
      return dtd.promise();
    },
    // 展开收缩组织架构菜单
    isShowMenu:function () {
      var self = this;
      $('.assignees-wrapper').unbind().on('click','.item',function (event) {
        if(event.target.className.indexOf('assignees-checkbox') > -1)return
        var _$this = $(this);
        var $menu = _$this;
        var arrowSign = $menu.find('.arrow-sign');  // 箭头指示图标
        var ulContainer = $menu.siblings('ul');
        var state = $menu.attr('data-state');   // 状态
        var load = $menu.data('load');  // 是否需要加载数据
        var type = $menu.data('type');  // 类型
        var id = $menu.data('id');      // 组织ID
        var index = $menu.data('index'); // 菜单级别
        var memberArr = self.assigneesData['userIds'];    // 节点处理人
        // 节点类型为成员时不再下级数据
        if(type == 'CY')return
        // 菜单打开关闭时更换对应状态
        // 如果没有子级菜单 则点击时不更换状态
        var updateMenuState = function () {
          if(state === 'close'){
            arrowSign.addClass('icon-GM－open').removeClass('icon-GM－stop')
            _$this.attr('data-state','open')
            ulContainer.show()
          }
          if(state === 'open'){
            arrowSign.removeClass('icon-GM－open').addClass('icon-GM－stop')
            _$this.attr('data-state','close')
            ulContainer.hide()
          }
        }

        // 如果没加载过下级数据 则加载新数据
        // 如果加载的子级菜单为成员,即父级类型为PO，则传false
        if(load === false){
          if(type == 'PO'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,true,memberArr)
              .done(function (data) {
                if(data.length)updateMenuState()
              })
          }
          if(type != 'PO'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,false)
              .done(function (data) {
                if(data.length)updateMenuState()
              })
          }
        }
      })

    },
    // 配置节点处理人
    configNodeUsers:function () {
      var self = this;
      $('.assignees-container').unbind().on('click','.assignees-checkbox',function (e) {
        var _$this = $(this);
        var $menu = _$this.parent('div');
        var ulContainer = $menu.siblings('ul');
        var state = $menu.attr('data-state');   // 状态
        var load = $menu.data('load');  // 是否需要加载数据
        var type = $menu.data('type');  // 类型
        var id = $menu.attr('data-id');      // 组织ID
        var name = _$this.siblings('.name').text(); // 节点名称
        var index = $menu.data('index'); // 菜单级别
        var dataIndex = 0;
        var checkBoxState = _$this.hasClass('active'); // true 为已选  false 为未选
        var memberArr = self.assigneesData['userIds'];    // 节点处理人

        // 选中的岗位 正选
        var positionMainDraw = function () {
          ulContainer.find('.assignees-checkbox').each(function () {
            if(!$(this).hasClass('active')){
              $(this).addClass('active')
              var id = $(this).parent('div').attr('data-id');
              var phone = $(this).parent('div').attr('data-userPhone');
              var account = $(this).parent('div').attr('data-userAccount');
              var name = $(this).siblings('.name').text();
              var obj = {}
              self.assigneesData['userIds'].push(id)
              self.assigneesData['userNames'].push(name)
              self.selectedMember.push({'userId':id,'userName':name,'userPhone':phone,'userAccount':account})
            }
          })
          _$this.addClass('active')
          self.dom.memberList(self.selectedMember)
        }
        if(type == 'PO' && checkBoxState === false){
          if( state == 'open')positionMainDraw()
          if( state == 'close'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,true,memberArr)
              .done(function (data) {
                if(data.length === 0)return
                positionMainDraw()
              })
          }
        }

        // 选中的岗位 反选
        var positionInvert = function () {
          ulContainer.find('.assignees-checkbox').each(function () {
            var id = $(this).parent('div').attr('data-id');
            var name = $(this).siblings('.name').text();
            var index = 0;
            $(this).removeClass('active')
            self.assigneesData['userNames'] = hlArrayUtil.deleteItem(self.assigneesData['userNames'],name)
            self.assigneesData['userIds'] = hlArrayUtil.deleteItem(self.assigneesData['userIds'],id)

            self.selectedMember.map(function(_item){
              if(_item.userId === id){
                self.selectedMember = hlArrayUtil.deleteIndexItem(self.selectedMember,index)
              }
              index++;
            })
          })
          _$this.removeClass('active')
          self.dom.memberList(self.selectedMember)
        }
        if(type == 'PO' && checkBoxState === true){
          if(state == 'open')positionInvert()
          if(state == 'close'){
            self.getOrganizationNodeData(id,index + 1,ulContainer,true,memberArr)
              .done(function (data) {
                if(data.length === 0)return
                positionInvert()
              })
          }
        }

        // 选中的岗位下成员 正选
        // 是否全部选中，若成员全部选中，则对应上级岗位勾选
        var isAllSelected = function () {
          var $gwMenu = _$this.parent().parent().parent().siblings('div');
          var $member = _$this.parent().parent().parent().find('.assignees-checkbox');
          var flag = true;
          $member.each(function () {
            if(!$(this).hasClass('active')){
              flag = false
            }
          })
          // flag为true 选中岗位 反之不选中岗位
          if(flag){
            $gwMenu.find('.assignees-checkbox').addClass('active');
          }else{
            $gwMenu.find('.assignees-checkbox').removeClass('active');
          }
        }
        // 选中成员
        var selectedMember = function(){
          var id = _$this.parent('div').attr('data-id');
          var phone = _$this.parent('div').attr('data-userPhone');
          var account = _$this.parent('div').attr('data-userAccount');
          var name = _$this.siblings('.name').text();
          var obj = {}

          _$this.addClass('active')
          // 如果该用户原来已添加过，则不再重复添加   如 一个人员在多部门
          if(self.assigneesData['userIds'].indexOf(id) === -1){
            self.assigneesData['userIds'].push(id)
            self.assigneesData['userNames'].push(name)
            self.selectedMember.push({'userId':id,'userName':name,'userPhone':phone,'userAccount':account})
          }
          if(self.assigneesData['userIds'].indexOf(id) !== -1){
            $('.assignees-checkbox ').each(function(_i,_el){
              if($(this).parents('div').attr('data-id') === id){
                $(this).addClass('active')
              }
            })
          }

          isAllSelected()
          self.dom.memberList(self.selectedMember)
        }
        // 反选成员
        var cancelSelectedMember = function(){
          var id = _$this.parent('div').attr('data-id');
          var phone = _$this.parent('div').attr('data-userPhone');
          var account = _$this.parent('div').attr('data-userAccount');
          var name = _$this.siblings('.name').text();
          var index = 0;

          _$this.removeClass('active')
          // 如果该用户在多部门 则同时将多部门的勾选取消掉
          self.assigneesData['userNames'] = hlArrayUtil.deleteItem(self.assigneesData['userNames'],name)
          self.assigneesData['userIds'] = hlArrayUtil.deleteItem(self.assigneesData['userIds'],id)
          $('.assignees-checkbox ').each(function(_i,_el){
            if($(this).parents('div').attr('data-id') === id){
              $(this).removeClass('active')
            }
          })
          self.selectedMember.map(function(_item){
            if(_item.userId === id){
              self.selectedMember = hlArrayUtil.deleteIndexItem(self.selectedMember,index)
            }
            index++;
          })
          isAllSelected()
          self.dom.memberList(self.selectedMember)
        }

        // 选中的岗位下成员 正选
        if(type == 'CY' && checkBoxState == false){
          selectedMember()
        }
        // 选中的岗位下成员 反选
        if(type == 'CY' && checkBoxState === true){
          cancelSelectedMember()
        }
        e.stopPropagation();
      })
    },
    // 删除已选组员
    removeSelectedMember:function(){
      var self = this;
      $('.selected-member-list').on('click','.delete-member',function(){
        var id = $(this).parent('ul').attr('data-id');
        var name = $(this).siblings('.name').text();
        var index = 0;
        self.assigneesData['userNames'] = hlArrayUtil.deleteItem(self.assigneesData['userNames'],name)
        self.assigneesData['userIds'] = hlArrayUtil.deleteItem(self.assigneesData['userIds'],id)
        self.selectedMember.map(function(_item){
          if(_item.userId === id){
            self.selectedMember = hlArrayUtil.deleteIndexItem(self.selectedMember,index)
          }
          index++;
        })
        $(this).parent('ul').remove()
        // 反选左侧树形图中已勾选的成员
        $('.member .assignees-checkbox').each(function(i,el){
          var memberId = $(this).parent('div').attr('data-id');
          var $gwMenu = $(this).parent().parent().parent().siblings('div');
          if(memberId === id){
            $(this).removeClass('active')
            $gwMenu.find('.assignees-checkbox').removeClass('active');
          }
        })
        if(self.selectedMember.length === 0){
          $('.no-member').show()
        }
      })
    },
    // 匹配负责人
    fzrDropdown:function(){
      var self = this;
      var sendUsersSearchRequest = function(val){
        hlhttp.get({
          url:'tenants/users/_search',
          data:{keyword:val},
          success:function(data){
            self.dom.fzrList(data)
            // 如果自己输入的名字  则匹配对应的id
            if(data.length !== 0){
              data.map(function(_item){
                if(_item.name == val || _item.phone == val){
                  $('.fzr').attr('data-name',_item.name)
                           .attr('data-tel',_item.phone)
                           .attr('data-id',_item.id)
                }
              })
              self.dom.fzrList(data)
            }else{
              $('.fzr').attr('data-name','')
                       .attr('data-tel','')
                       .attr('data-id','')
            }
          }
        })
      }

      $('.fzr').bind('input',function(){
        var value = $(this).val().trim()
        window.setTimeout(function(){
          sendUsersSearchRequest(value)
        },150)
      })
      $('.fzr').bind('blur',function(){
        if(!$('.fzr').attr('data-name')){$('.fzr').val('')}
      })
      $('.fzr-ipt-select').on('click','li',function(){
        $('.fzr').val($(this).find('.name').text())
        $('.fzr').attr('data-name',$(this).find('.name').text())
                 .attr('data-tel',$(this).find('.tel').text())
                 .attr('data-id',$(this).attr('data-id'))
        $('.fzr-ipt-select ul').hide()
      })
      $(document).click(function(){
        $('.fzr-ipt-select ul').hide()
      })
    },
    clearData:function(){
      this.assigneesData.userIds = [];
      this.assigneesData.userNames = [];
      $('.assignees-container .assignees-wrapper').empty()
      $('.selected-member-list ul').remove()
      $('.grp-ipt').val('')
      $('.fzr').val('')
      $('.fzr').attr('data-name','').attr('data-id','').attr('data-tel','')
      $('.no-member').show()
    },
    event:function(){
      var self = this;
      $('.wkp-pop-close-btn').click(function(){
        $('.wkp-pop').hide()
        $('.backdrop').hide()
        self.clearData()
      })

      $('.fzr-ipt-select li').click(function(){
        $('.fzr').val($(this).find('.name').text())
        $('.fzr').attr('data-tel',$(this).find('.tel').text())
        $('.fzr').attr('data-name',$(this).find('.name').text())
      })

      $('.save-wkp').click(function(){
        var state = JSON.parse(window.localStorage.getItem('wgData')).state
        if(state === 'add')self.saveCreate()
        if(state === 'edit')self.saveEdit()
      })
    },
    dom:{
      // 非成员外的组织节点
      organizationNode:function (data,containerNode) {
        var html = '';
        data.map(function (item) {
          // id  组织ID  type 组织类型  index 组织菜单级别  state 菜单状态（打开、关闭） load 点击菜单时是否需要加载新数据
          // 非岗位类型无复选框
          var checkBoxHtml = ''
          if(item.type == 'PO')checkBoxHtml = '<span class="assignees-checkbox"></span>'

          html += '<li class="cursor">' +
            '<div class="item item-' + item.index + '" data-id="' + item.id + '" data-type="' + item.type + '" data-index="' + item.index + '" data-state="close" data-load="false">' +
            '<span class="hl-icon icon-GM－stop arrow-sign"></span>' +
            checkBoxHtml +
            '<i class="name">' + item.shortName + '</i>' +
            '</div>' +
            '<ul class="container-' + item.index + '"></ul>' +
            '</li>'
        })
        containerNode.html(html)
      },
      // 成员节点
      memberNode:function (data,member,containerNode) {
        var html = '';
        var isAllSelected = true;

        if(data.length === 0)return
        data.map(function (item) {
          var isSelected = '';
          // 如果加载的组织成员在成员数组中，则选中
          for(var i = 0 ; i < member.length; i++){
            if(member[i] == item.id){
              isSelected = 'active'
              break;
            }
          }
          if(isSelected === '')isAllSelected = false

          // id  组织ID  type 组织类型  index 组织菜单级别  state 菜单状态（打开、关闭） load 点击菜单时是否需要加载新数据
          html += '<li>' +
            '<div class="member item item-' + item.index + '" data-userPhone="' + item.userPhone + '" data-userAccount="' + item.userAccount + '" data-userName="' + item.shortName + '" data-id="' + item.id + '" data-type="' + item.type + '" data-index="' + item.index + '" data-state="close" data-load="false">' +
            '<span class="assignees-checkbox ' + isSelected + '"></span>' +
            '<i class="name">' + item.shortName + '</i>' +
            '</div>' +
            '<ul class="container-' + item.index + '"></ul>' +
            '</li>'
        })

        // 如果该岗位下所有成员被选中，则该岗位被选中
        if(isAllSelected){
          containerNode.siblings('div').find('.assignees-checkbox').addClass('active')
        }
        containerNode.html(html)
      },
      // 选过的组织成员
      memberList:function(data,length){
        var html = '';
        data.map(function(item){
          html += '<ul class="dy-flex selected-member-item" data-id="'+ item.userId +'">' +
            '<li class="dy-fx-2 name">' + item.userName + '</li>' +
            '<li class="dy-fx-2">' + item.userAccount + '</li>' +
            '<li class="dy-fx-2">' + item.userPhone + '</li>' +
            '<li class="dy-fx-1 delete-member cursor">' +
              '<span class="icon-Gm-delete"></span>' +
            '</li>' +
          '</ul>'
        })
        $('.selected-member-list .have-member').html(html)
        $('.no-member').hide()
      },
      fzrList:function(data){
        var html = '';
        data.map(function(_item){
          html += '<li data-id="' + _item.id + '"><i class="name">' + _item.name + '</i><i class="tel">'+  _item.phone + '</i></li>'
        })
        $('.fzr-ipt-select ul').html(html).show()
      }
    }
  }

  window.workingGroup = workingGroup
  workingGroup.init()
}())
